package me.zhengjie.modules.app.award;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.result.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/award/history")
public class AwardHistoryController {

    @PostMapping("/login")
    public R login(@RequestBody JSONObject jsonObject){
        // 请求URL
        String url = "http://we39.idcboss033.com:23311/user/login.php?xtype=login";

        // JSON参数
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("{\"username\":\"");
        stringBuffer.append(jsonObject.getString("username"));
        stringBuffer.append("\",");
        stringBuffer.append("\"password\":\"");
        stringBuffer.append(jsonObject.getString("password"));
        stringBuffer.append("\",");
        stringBuffer.append("\"code\":\"");
        stringBuffer.append(jsonObject.getString("code"));
        stringBuffer.append("\",");
        stringBuffer.append("\"ismobi\":\"");
        stringBuffer.append(jsonObject.getInteger("ismobi"));
        stringBuffer.append("\"}");

//        String jsonInputString = "{\"username\":\"21\",\"password\":\"12\",\"code\":\"12\",\"ismobi\":0}";

        String jsonInputString = stringBuffer.toString();
        try{
            return requestJson(url,jsonInputString);
        }catch (Exception e){
            log.info("登录异常",e);
        }
        return R.success();
    }

    @PostMapping("/query")
    public R query(@RequestBody JSONObject jsonObject){
        // 请求URL
        String url = "http://we39.idcboss033.com:23311/user/historyrep.php?xtype=list";

        // JSON参数
        String jsonInputString = jsonObject.toJSONString();
        log.info("开奖记录请求参数：{}",jsonInputString);
        try{
//           return requestFormData(url,"{\"data\":"+jsonInputString +"}");
            Map param = new HashMap();
            param.put("data",jsonInputString);
            return requestFormData(url, param );
        }catch (Exception e){
            log.info("查询开奖历史异常",e);
        }
        return R.success();
    }

    private R requestJson(String url,String jsonInputString){
        try{
            // 创建连接
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Cookie","PHPSESSID=8qcstetleqekdur95bi027vfu0");
            connection.setRequestProperty("Host", "we39.idcboss033.com:23311"); // 设置Host头

            connection.setDoOutput(true);

            // 发送请求
            try(OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            try(BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println("Response: " + response);
                return R.success(response);
            }
        }catch (Exception e){
            log.info("请求异常",e);
        }
        return R.success();

    }

    private R requestFormData(String urlPath,Map param) throws IOException{
        HttpURLConnection connection = null;
        OutputStream outputStream = null;
        BufferedReader reader = null;

        try {
            URL requestUrl = new URL(urlPath);
            connection = (HttpURLConnection) requestUrl.openConnection();

            // 设置请求属性
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
            connection.setRequestProperty("Accept", "application/json, text/plain, */*");
            connection.setRequestProperty("Cookie","PHPSESSID=8qcstetleqekdur95bi027vfu0");
            connection.setRequestProperty("Host", "we39.idcboss033.com:23311"); // 设置Host头

            // 构建请求体
            String postData = buildFormData(param);

            // 设置Content-Length
            connection.setRequestProperty("Content-Length", Integer.toString(postData.getBytes(StandardCharsets.UTF_8).length));

            // 发送请求
            outputStream = connection.getOutputStream();
            outputStream.write(postData.getBytes(StandardCharsets.UTF_8));
            outputStream.flush();

            // 获取响应
            int responseCode = connection.getResponseCode();
            System.out.println("HTTP状态码: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                return R.success(response.toString());
            } else {
                // 读取错误信息
                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8));
                StringBuilder errorResponse = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    errorResponse.append(line);
                }
                throw new IOException("服务器返回错误: " + responseCode + " - " + errorResponse.toString());
            }

        } finally {
            // 关闭资源
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * 构建form-urlencoded格式的请求体
     */
    private static String buildFormData(Map<String, String> params) throws UnsupportedEncodingException {
        StringBuilder formData = new StringBuilder();
        boolean first = true;

        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (first) {
                first = false;
            } else {
                formData.append("&");
            }

            formData.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            formData.append("=");
            formData.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return formData.toString();
    }
}
